package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.log.annotation.Log;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.*;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.vo.PersonalFilesTreeVo;
import cn.cdeden.knowledge.enums.FileEnums;
import cn.cdeden.knowledge.enums.TeamParamEnum;
import cn.cdeden.knowledge.mapper.EnterpriseFilesTreeMapper;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.knowledge.utils.MyUtil;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.resource.api.domain.RemoteFilesDownload;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.enums.EnterprisePermTypeEnum;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.undertow.util.BadRequestException;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cdeden.knowledge.mapper.FilesShareMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = FilesShareService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FilesShareServiceImpl extends ServiceImpl<FilesShareMapper, FilesShare> implements FilesShareService{

    private final PersonalFilesTreeService personalFilesTreeService;

    private final FilesShareMapper filesShareMapper;

    private final TeamFilesTreeService teamFilesTreeService;

    private final TeamRelevanceRoleService teamRelevanceRoleService;

    private final EnterpriseFilesTreeMapper enterpriseFileMapper;

    @DubboReference(check = false)
    private final RemoteUserService remoteUserService;


    private final EnterprisePermService enterprisePermService;

    @Override
    public TableDataInfo<FilesShareDto> queryByFileId(String fileId, String type, String teamId, Pageable pageable) throws BadRequestException {
        if (StringUtils.isBlank(type)) {
            throw new BadRequestException("错误的分享查询处理");
        }
        String[] split = fileId.split(",");
        Arrays.sort(split);
        fileId = String.join(", ", split);
        if (split.length > 1) {


            IPage<FilesShare> queryPage = PageUtil.toMybatisPage(pageable);
            IPage<FilesShare> page = filesShareMapper.selectPage(queryPage, new QueryWrapper<FilesShare>()
                    .eq(fileId != null, "file_id", fileId)
//                    .apply(fileId != null, "file_id = '" + fileId + "' or FIND_IN_SET ( file_id , '" + fileId + "' )")
                    .eq(type != null, "share_type", type)
                    .eq(teamId != null, "team_id", teamId)

            );

            TableDataInfo<FilesShare> build = TableDataInfo.build(page);
            TableDataInfo<FilesShareDto> filesShareDtoTableDataInfo = MapstructUtils.convertTableDataInfo(build, FilesShareDto.class);

            List<FilesShareDto> content = filesShareDtoTableDataInfo.getRows();
            for (int i = 0; i < content.size(); i++) {
                FilesShareDto filesShareDto = content.get(i);
                String accessibleId = filesShareDto.getAccessibleId();
                if (StringUtils.isNotBlank(accessibleId)) {
                    try {
                        List<Long> idList = Arrays.stream(accessibleId.split(","))
                            .filter(StringUtils::isNotBlank) // 确保字符串非空
                            .map(Long::valueOf)              // 将字符串转换为 Long 类型
                            .collect(Collectors.toList());
                        List<RemoteUserVo> remoteUserVos = remoteUserService.selectListByIds(idList);
                        filesShareDto.setUsers(remoteUserVos);
                        content.set(i, filesShareDto);
                    } catch (Exception e) {

                    }
                }
            }
            filesShareDtoTableDataInfo.setRows(content);
            return filesShareDtoTableDataInfo;
        } else {
            IPage<FilesShare> queryPage = PageUtil.toMybatisPage(pageable);
            IPage<FilesShare> page = filesShareMapper.selectPage(queryPage, new QueryWrapper<FilesShare>()
                .apply(fileId != null, "file_id = '" + fileId + "' or FIND_IN_SET ( '" + fileId + "',file_id  )")
                .eq(type != null, "share_type", type)

            );
            TableDataInfo<FilesShare> build = TableDataInfo.build(page);
            TableDataInfo<FilesShareDto> filesShareDtoTableDataInfo = MapstructUtils.convertTableDataInfo(build, FilesShareDto.class);
            List<FilesShareDto> content = filesShareDtoTableDataInfo.getRows();
            for (int i = 0; i < content.size(); i++) {
                FilesShareDto filesShareDto = content.get(i);
                String accessibleId = filesShareDto.getAccessibleId();
                if (StringUtils.isNotBlank(accessibleId)) {
                    try {
                        List<Long> idList = Arrays.stream(accessibleId.split(","))
                            .filter(StringUtils::isNotBlank) // 确保字符串非空
                            .map(Long::valueOf)              // 将字符串转换为 Long 类型
                            .collect(Collectors.toList());
                        List<RemoteUserVo> users = remoteUserService.selectListByIds(idList);
                        filesShareDto.setUsers(users);
                        content.set(i, filesShareDto);
                    } catch (Exception e) {

                    }
                }
            }
            filesShareDtoTableDataInfo.setRows(content);
            return filesShareDtoTableDataInfo;
        }
    }


    @Override
    public FilesShare getById(Long id) {
        return filesShareMapper.selectById(id);
    }



    @Override
    public FilesShareDto findById(Long id) {
        FilesShareDto filesShareDto = MapstructUtils.convert(getById(id), FilesShareDto.class);
        if (filesShareDto.getAccessibleId() != null && !"".equals(filesShareDto.getAccessibleId())) {
            String[] split1 = filesShareDto.getAccessibleId().split(",");
            List<Long> idList = Arrays.stream(split1)
                .filter(StringUtils::isNotBlank)
                .map(Long::valueOf)
                .collect(Collectors.toList());
            List<RemoteUserVo> users = remoteUserService.selectListByIds(idList);
//            List<SysUser> users = userMapper.selectBatchIds(Arrays.asList(split1));
            filesShareDto.setUsers(users);
        }
        return filesShareDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FilesShare updateById(FilesShareDto resources) {
        LoginUser user = LoginHelper.getLoginUser();
        FilesShare entity = MapstructUtils.convert(resources, FilesShare.class);

        LambdaUpdateWrapper<FilesShare> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(FilesShare::getId, entity.getId());

        //下载次数和可访问次数单独判断
        if (entity.getVisitsNumber() == null) {
            updateWrapper.set(FilesShare::getVisitsNumber, null);
        }
        if (entity.getDownloadsNumber() == null) {
            updateWrapper.set(FilesShare::getDownloadsNumber, null);
        }

        if (entity.getDeadline() == null) {
            updateWrapper.set(FilesShare::getDeadline, null);
        }

        updateWrapper.set(FilesShare::getUpdateBy, user.getUsername());
        updateWrapper.set(FilesShare::getUpdateId, user.getUserId());
        updateWrapper.set(FilesShare::getUpdateTime, new Date());


        filesShareMapper.update(entity, updateWrapper);

        FilesShare filesShare = filesShareMapper.selectById(resources.getId());
        //TODO 消息相关（待补充）
//        toMessage(filesShare, FileUserUtils.getUser());
        return filesShare;
    }

    @Override
    public TableDataInfo<FilesShareDto> queryBySPerson(String userId, String type, String teamId, String name, Pageable pageable) {
        IPage<FilesShare> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FilesShare> page = filesShareMapper.selectPage(queryPage,
            new QueryWrapper<FilesShare>()
                .eq(userId != null, "person_id", userId)
                .eq(type != null, "share_type", type)
                .eq(teamId != null, "team_id", teamId)
                .like(name != null, "name", name)
                .orderByDesc("create_time")
        );
        TableDataInfo<FilesShare> build = TableDataInfo.build(page);
        return MapstructUtils.convertTableDataInfo(build, FilesShareDto.class);
    }

    @Override
    public Map<String, Object> queryShareFileUrl(String id, String fileId) {
        FilesShare filesShare = this.lambdaQuery().eq(FilesShare::getId, id).eq(FilesShare::getStatus, 1).one();
        if (ObjectUtils.isEmpty(filesShare)) {
            throw new RuntimeException("分享的链接不存在了");
        }
        FilesTree convert = null;
        List<String> collect = null; //查询出所有父级
        //查询出来
        FileEnums fileEnums = FileEnums.find(filesShare.getShareType());
        switch (fileEnums) {
            case PERSONAL_FILE:
                PersonalFilesTree one = personalFilesTreeService.lambdaQuery().eq(PersonalFilesTree::getId, fileId).isNull(PersonalFilesTree::getDeleteId).one();
                convert = MapstructUtils.convert(one, FilesTree.class);
                collect = Arrays.asList(convert.getSuperiorsIds().split(","));
                break;
            case TEAM_FILE:
                TeamFilesTree teamFiles = teamFilesTreeService.lambdaQuery()
                    .eq(TeamFilesTree::getId, fileId)
                    .isNull(TeamFilesTree::getDeleteId)
                    .one();

                List<TeamFilesTree> teamTrees = teamFilesTreeService.selectSuperiorAll(fileId);
                collect = teamTrees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList()); //查询出所有父级
                convert = MapstructUtils.convert(teamFiles, FilesTree.class);
                break;
//            case ENTERPRISE_FILE:
//                EnterpriseFilesTree enterpriseTree = enterpriseFileMapper.lambdaQuery()
//                    .eq(EnterpriseFilesTree::getId, fileId)
//                    .isNull(EnterpriseFilesTree::getDeleteId)
//                    .one();
//
//                List<EnterpriseFilesTree> trees = enterpriseFileMapper.selectSuperiorAll(fileId);
//                collect = trees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList()); //查询出所有父级
//
//                convert = MapstructUtils.convert(enterpriseTree, FilesTree.class);
//                break;
            default:
                throw new RuntimeException("错误的分享类型");
        }

        if (convert == null) {
            throw new RuntimeException("文件不存在");
        }
        convert.setLibraryType(fileEnums.getCode());
        //处理查询的文件上级文件 是否 存在
        String shareFileId = filesShare.getFileId();
        String[] shareFileIdSplit = shareFileId.split(",");
        collect = new ArrayList<>(collect);
        collect.add(fileId); //添加当前查询的编号  之前全部是父亲

        String[] split = collect.toArray(new String[collect.size()]);

        if (!Arrays.stream(shareFileIdSplit)
            .anyMatch(num -> StringUtils.equalsAny(num, split))) {
            throw new RuntimeException("该文件不是，这个分享链接中的文件");
        }

        Long userId = null;
        try {
            userId = LoginHelper.getUserId();
        } catch (Exception e) {
//            log.info("获取用户ID时发生异常: {}", e.getMessage());
        }
        queryPermissions(filesShare, ShareGetInfoDto.builder().userId(userId).build());
        Map<String, Object> map = new HashMap<>();
        map.put("info", convert);
        map.put("shareInfo", filesShare);
        return map;
    }

    @Override
    public FilesShare insert(FilesShareDto resources) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser();
        String shareType = resources.getShareType();
        String fileId = resources.getFileId();
        if (StringUtils.isBlank(shareType)) {
            throw new BadRequestException("错误的分享查询处理");
        }
        String[] split = fileId.split(",");

        Arrays.sort(split);
        String join = String.join(", ", split);
        resources.setFileId(join);
        //验证不同库的数据权限
        if (StringUtils.equals(shareType, FileEnums.ENTERPRISE_FILE.getCode())) {
            //企业库
            for (String s : split) {
                if (!enterprisePermService.checkPermission(Long.valueOf(s), EnterprisePermTypeEnum.MANAGE, null))
                    throw new BadRequestException("没有分享权限");
            }
        } else if (StringUtils.equals(shareType, FileEnums.TEAM_FILE.getCode())) {
            //TODO 团队库待补充
//            //团队库
//            for (String s : split) {
//                if (!teamRelevanceRoleService.checkPermission(s, resources.getTeamId(), user, TeamParamEnum.SHARE.getParam()))
//                    throw new BadRequestException("没有分享权限");
//            }
        } else {

        }

        //生成链接
        String linkAddress = resources.getLinkAddress();
        if (linkAddress == null || "".equals(linkAddress)) {
            throw new BadRequestException("未知异常");
        }

        String hash = MyUtil.getUUID(12);
        String link = linkAddress + "/enjoyLink?hash=" + hash;

//        if(resources.getShareForm().intValue() == 1){
//            resources.setPassword(MyUtil.getUUID(4));
//        }
        resources.setHash(hash);
        resources.setLinkAddress(link);
        String accessibleId = resources.getAccessibleId();

        if (StringUtils.isNotBlank(accessibleId)) {
            List<String> list = Arrays.asList(accessibleId.split(","));
            if (CollectionUtils.isNotEmpty(list)) {
                StringJoiner ji = new StringJoiner(",");
                for (String s : list) {
                    if (StringUtils.isNotBlank(s) && !StringUtils.equals(s, String.valueOf(user.getUserId()))) {  //不为不等于自己
                        ji.add(s);
                    }
                }
                resources.setAccessibleId(ji.toString());
            } else {
                resources.setAccessibleId(null);
            }
        }


        FilesShare entity = MapstructUtils.convert(resources, FilesShare.class); //修改类
        entity.setCreateTime(new Date());
        entity.setCreateBy(user.getUsername());
        filesShareMapper.insert(entity); //保存数据


        //TODO 消息待补充
//        toMessage(entity, user);

        return entity;
    }

    @Override
    public TableDataInfo<FilesShareDto> queryBySdPerson(String userId, String type, String teamId, String name, Pageable pageable) {
        IPage<FilesShare> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FilesShare> page = filesShareMapper.selectPage(queryPage,
            new QueryWrapper<FilesShare>()
                .eq("share_type", type)
                .eq(teamId != null, "team_id", teamId)
                .like(name != null, "name", name)
                .apply(userId != null, " ( accessible_id = '" + userId + "' or FIND_IN_SET ( '" + userId + "' , accessible_id  ) )")
                .orderByDesc("create_time")
        );
        TableDataInfo<FilesShare> build = TableDataInfo.build(page);
        return MapstructUtils.convertTableDataInfo(build, FilesShareDto.class);
    }

    @Override
    public FilesShareDto shareGetInfo(FilesShare filesShare) {
        FilesShareDto convert = MapstructUtils.convert(filesShare, FilesShareDto.class);
        FileEnums fileEnums = FileEnums.find(convert.getShareType());
        if (fileEnums == null) {
            throw new RuntimeException("错误的分享类型");
        }
        Long personId = convert.getPersonId();
        convert.setPersonNickname(String.valueOf(personId));

        switch (fileEnums) {
            case PERSONAL_FILE:
                return shareGetInfoPersonal(convert);
            case TEAM_FILE:
                return shareGetInfoTeam(convert);
            case ENTERPRISE_FILE:
                return shareGetInfoEnterprise(convert);
            default:
                throw new RuntimeException("错误的分享类型");
        }
    }

    @Override
    public FilesShareDto shareDirList(ShareGetInfoDto shareGetInfoDto) {
        String pid = String.valueOf(shareGetInfoDto.getPid());

        FilesShare filesShare = this.getOne(new QueryWrapper<FilesShare>().eq("hash", shareGetInfoDto.getHash()).eq("status", 1));
        FilesShareDto convert = MapstructUtils.convert(filesShare, FilesShareDto.class);

        List<String> collect = null; //查询出所有父级
        FileEnums fileEnums = FileEnums.find(convert.getShareType());
        if (fileEnums == null) {
            throw new RuntimeException("错误的分享类型");
        }

        switch (fileEnums) {
            case PERSONAL_FILE:
                List<PersonalFilesTree> personalFilesTrees = personalFilesTreeService.lambdaQuery()
                    .eq(PersonalFilesTree::getParentId, pid).isNull(PersonalFilesTree::getDeleteId).list();
                if (personalFilesTrees.size() > 0) {
                    collect = Arrays.asList(personalFilesTrees.get(0).getSuperiorsIds().split(","));
                    convert.setPersonalFilesTreeVos(MapstructUtils.convert(personalFilesTrees, PersonalFilesTreeVo.class));
                }
                break;
            case TEAM_FILE:
//                return shareGetInfoTeam(convert);
                List<TeamFilesTree> teamFilesTreesOld = teamFilesTreeService.lambdaQuery().eq(TeamFilesTree::getParentId, pid).isNull(TeamFilesTree::getDeleteId).list();

//                List<TeamFilesTree> teamFilesTreesOld = teamFilesTreeService.list(new QueryWrapper<TeamFilesTree>().eq("parent_id", pid).isNull("delete_id"));

                List<TeamFilesTree> teamFilesTrees = new ArrayList<>();

                for (TeamFilesTree teamFilesTree : teamFilesTreesOld) {
                    //判断是否有权限
                    if (teamRelevanceRoleService.checkPermission(String.valueOf(teamFilesTree.getId()), teamFilesTree.getTeamId(), remoteUserService.getUserInfo(convert.getPersonId()), TeamParamEnum.SHARE.getParam())) {
                        teamFilesTrees.add(teamFilesTree);
                    }
                }

//                if (teamFilesTrees.size() > 0) {
//                    convert.setTeamFilesTreeDtos(MapstructUtils.convert(teamFilesTrees, TeamFilesTreeDto.class));
//                }
//                List<TeamFilesTree> teamTrees = teamFilesTreeService.selectSuperiorAll(pid);
//                collect = teamTrees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList()); //查询出所有父级

                if (teamFilesTrees.size() > 0) {
                    List<TeamFilesTree> teamTrees = teamFilesTreeService.selectSuperiorAll(pid);
                    collect = teamTrees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList());
                    convert.setTeamFilesTreeDtos(MapstructUtils.convert(teamFilesTrees, TeamFilesTreeDto.class));
                }
                break;
            case ENTERPRISE_FILE:
                List<EnterpriseFilesTree> enterpriseFilesTrees = enterpriseFileMapper.selectList(new QueryWrapper<EnterpriseFilesTree>().eq("parent_id", pid).isNull("delete_id"));
                if (enterpriseFilesTrees.size() > 0) {
                    convert.setEnterpriseFilesTreeDtos(MapstructUtils.convert(enterpriseFilesTrees, EnterpriseFilesTreeDto.class));
                }

                List<EnterpriseFilesTree> trees = enterpriseFileMapper.selectSuperiorAll(pid);
                collect = trees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList()); //查询出所有父级

                break;
            default:
                throw new RuntimeException("错误的分享类型");
        }

        //处理查询的文件上级文件 是否 存在
        if (CollectionUtils.isEmpty(collect)) {
            throw new RuntimeException("无法获取该链接的下级文件");
        }

        String shareFileId = filesShare.getFileId();
        String[] shareFileIdSplit = shareFileId.split(",");

        String[] split = collect.toArray(new String[collect.size()]);

        if (!Arrays.stream(shareFileIdSplit)
            .anyMatch(num -> StringUtils.equalsAny(num, split))) {
            throw new RuntimeException("该文件不是，这个分享链接中的文件");
        }


        return convert;
    }

    @Override
    public void delAllBySPerson(String userId, String type, String teamId) {
        List<FilesShare> filesShares = filesShareMapper.selectList(new QueryWrapper<FilesShare>()
            .eq("person_id", userId)
            .eq("share_type", type)
            .eq(teamId != null, "team_id", teamId)
        );
        List<Long> ids = new ArrayList<>();
        filesShares.forEach(filesShare -> {
            Boolean aBoolean = MyUtil.isDeadTime(filesShare.getDeadline()) ? ids.add(filesShare.getId()) : null;
        });
        if (CollectionUtils.isNotEmpty(ids)) {
//            filesShareMapper.deleteBatchIds(ids);
            filesShareMapper.deleteByIds(ids);
        }
    }


    @Override
    public List<RemoteFilesDownload> shareDownload(ShareDownloadFilesDto fileInfo) {
        List<String> fileIds = fileInfo.getFileIds();
        FilesShare filesShare = this.lambdaQuery().eq(FilesShare::getId, fileInfo.getId()).eq(FilesShare::getStatus, 1).one();
        if (ObjectUtils.isEmpty(filesShare)) {
            throw new RuntimeException("分享的链接不存在了");
        }
        Set<String> collect = new HashSet<>(); //查询出所有父级
        List<RemoteFilesDownload> downloadFiles = null;

        //查询出来
        FileEnums fileEnums = FileEnums.find(filesShare.getShareType());
        switch (fileEnums) {
//            case PERSONAL_FILE:
//                downloadFiles = personalFilesTreeService.folderSonFiles(fileIds, true);
//                //获取下载文件的父级全部的编号
//                List<String> list = downloadFiles.stream().map(TreeDownloadFiles::getSuperiorsIds)
//                    .collect(Collectors.toList());
//                for (String s : list) {
//                    String[] shareFileIdSplit = s.split(",");
//                    collect.addAll(Arrays.asList(shareFileIdSplit));
//                }
//                break;
            case TEAM_FILE:
                downloadFiles = teamFilesTreeService.teamDownloadFile(fileIds, filesShare.getPersonId());
//                downloadFiles = teamFilesTreeService.folderSonFiles(fileIds, true, String.valueOf(filesShare.getPersonId()));
                for (RemoteFilesDownload file : downloadFiles) {
                    List<TeamFilesTree> teamTrees = teamFilesTreeService.selectSuperiorAll(String.valueOf(file.getId()));
                    collect.addAll(teamTrees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList())); //查询出所有父级
                }
                break;
//            case ENTERPRISE_FILE:
//                List<TreeDownloadFiles> enterpriseFiles = enterpriseFileService.folderSonFiles(fileIds, String.valueOf(filesShare.getPersonId()), true, EnterprisePermTypeEnum.EDITOR);
//                for (TreeDownloadFiles file : enterpriseFiles) {
//                    List<EnterpriseFilesTree> filesTrees = enterpriseFileMapper.selectSuperiorAll(String.valueOf(file.getId()));
//                    collect.addAll(filesTrees.stream().map(tree -> tree.getId().toString()).collect(Collectors.toList())); //查询出所有父级
//                }
//                break;
//                throw new RuntimeException("分享企业的文件没有下载功能没有实现");
            default:
                throw new RuntimeException("错误的分享类型");
        }


        if (downloadFiles == null) {
            throw new RuntimeException("分享文件不存在无法下载");
        }

        //处理查询的文件上级文件 是否 存在
        String shareFileId = filesShare.getFileId();
        String[] shareFileIdSplit = shareFileId.split(",");
        collect = new HashSet<String>(collect) {
        };
        collect.addAll(fileIds); //添加当前查询的编号  之前全部是父亲

        String[] split = collect.toArray(new String[collect.size()]);

        if (!Arrays.stream(shareFileIdSplit).anyMatch(num -> StringUtils.equalsAny(num, split))) {
            throw new RuntimeException("该文件不是，这个分享链接中的文件");
        }

        Long userId = null;
        try {
            userId = LoginHelper.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
//            log.info("获取用户ID时发生异常: {}", e);
        }
        queryPermissions(filesShare, ShareGetInfoDto.builder().userId(userId).build());


        return downloadFiles;
    }


    private void queryPermissions(FilesShare filesShare, ShareGetInfoDto info) {
        String accessibleId = filesShare.getAccessibleId();
        if (StringUtils.isNotBlank(accessibleId)) {
            String[] split = accessibleId.split(",");
            //分享人可以直接访问
            String userId = String.valueOf(info.getUserId());
            if (StringUtils.equals(String.valueOf(filesShare.getPersonId()), userId)) {
                //可访问者可以访问
                if (!StringUtils.equalsAny(userId, split) && !filesShare.getPersonId().toString().equals(userId)) {
                    throw new RuntimeException("当前用户没有权限查看");
                }
            }
        }
    }
    /**
     * @param convert
     * @return com.cdyd.ecm.modules.share.service.dto.FilesShareDto
     * @Description // 个人
     **/
    private FilesShareDto shareGetInfoPersonal(FilesShareDto convert) {
        List<PersonalFilesTreeVo> personalFilesTreeVos = new ArrayList<>();
        String[] split = convert.getFileId().split(",");

        List<PersonalFilesTree> trees = personalFilesTreeService.lambdaQuery().in(PersonalFilesTree::getId, split).isNull(PersonalFilesTree::getDeleteId).list();
        personalFilesTreeVos.addAll(MapstructUtils.convert(trees, PersonalFilesTreeVo.class));
        convert.setPersonalFilesTreeVos(personalFilesTreeVos);
        return convert;
    }

    /**
     * @param convert
     * @return com.cdyd.ecm.modules.share.service.dto.FilesShareDto
     * @author Yu.
     * @Description // 团队
     * @Date 2023/12/5 11:37
     **/
    private FilesShareDto shareGetInfoTeam(FilesShareDto convert) {
        List<TeamFilesTreeDto> teamFilesTreeDtos = new ArrayList<>();
        String[] split = convert.getFileId().split(",");

        List<TeamFilesTree> filesTrees = new ArrayList<>();
        for (String s : split) {
            TeamFilesTree teamFilesTree = teamFilesTreeService.lambdaQuery().eq(TeamFilesTree::getId, s).isNull(TeamFilesTree::getDeleteId).one();
//            //判断分享人是否有权限
            if (teamRelevanceRoleService.checkPermission(String.valueOf(teamFilesTree.getId()), teamFilesTree.getTeamId(), remoteUserService.getUserInfo(convert.getPersonId()), TeamParamEnum.SHARE.getParam())) {
                filesTrees.add(teamFilesTree);
            }
        }

        teamFilesTreeDtos.addAll(MapstructUtils.convert(filesTrees, TeamFilesTreeDto.class));
        convert.setTeamFilesTreeDtos(teamFilesTreeDtos);
        return convert;
    }


    /**
     * @param convert
     * @return com.cdyd.ecm.modules.share.service.dto.FilesShareDto
     * @author Yu.
     * @Description // 企业
     * @Date 2023/12/5 11:37
     **/
    private FilesShareDto shareGetInfoEnterprise(FilesShareDto convert) {
        List<EnterpriseFilesTreeDto> enterpriseFilesTreeDtos = new ArrayList<>();
        String[] split = convert.getFileId().split(",");
        List<EnterpriseFilesTree> filesTrees = enterpriseFileMapper.selectList(new QueryWrapper<EnterpriseFilesTree>().in("id", split).isNull("delete_id"));
        enterpriseFilesTreeDtos.addAll(MapstructUtils.convert(filesTrees, EnterpriseFilesTreeDto.class));
        convert.setEnterpriseFilesTreeDtos(enterpriseFilesTreeDtos);
        return convert;
    }



}
